package com.ssd.job;

import com.alibaba.fastjson2.JSON;
import com.ssd.api.order.OrderApi;
import com.ssd.api.order.dto.OrderDetailViewModel;
import com.ssd.api.payment.dto.msg.TradeStatusMsg;
import com.ssd.mixly.service.IMqttService;
import com.ssd.mixly.service.ListenMqtt;
import com.ssd.mixly.service.impl.MqttServiceImpl;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 自定义消息处理类
 */
@Component
public class ListenMqttImpl implements ListenMqtt {
    @Resource
    private OrderApi orderApi;//远程调用对象-

    @Override
    public void listen(String topic, String message) {
        System.err.println("监听到支付消息");
        System.err.println("主题："+topic);
        System.err.println("消息："+message);
        TradeStatusMsg tradeStatusMsg= JSON.parseObject(message, TradeStatusMsg.class);
        System.out.println("解析后的数据："+tradeStatusMsg);

        if(tradeStatusMsg.getStatusCode()==4){
            String orderNo=orderApi.getOrderNo(tradeStatusMsg.getTransactionId());
            List<OrderDetailViewModel> orderDetailViewModels= orderApi.getOrderList(orderNo);
            // 发送消息到 mixly，通知设备运转
            IMqttService service = new MqttServiceImpl();
            for (OrderDetailViewModel orderDetailViewModel:orderDetailViewModels) {
                String msg="";
                if(orderDetailViewModel.getSkuId()==1){
                    msg="1-2";
                }else if(orderDetailViewModel.getSkuId()==5){
                    msg="1-1";
                }else if(orderDetailViewModel.getSkuId()==7){
                    msg="1-3";
                }
                try {
                    service.send("send",msg);
                } catch (MqttException e) {
                    throw new RuntimeException(e);
                }
            }
            //TODO 出货完成，前端响应
        }
    }
}